/**
 * Created by kevin on 2017/6/2.
 */
var express = require('express');
var Users = require('../models/Users');
var router = express.Router();
var Components = require('../models/Components');
var Robots = require('../models/Robots');
var Repos = require('../models/Repos');

var ucheck = require('../utils/ucheck');

var Delegater = require('../models/Delegaters');

var GitUsers = require('../models/GitUsers');

var scripter = require('../utils/scripter');

var stream = require('../utils/stream');

var versionC = require('../utils/version');

var dingding = require('../utils/dingding');


router.get('/*',function (req,res,next) {
    ucheck.hasLogin(res,function (has) {
        if (!has) {
            req.flash('error', '请先登录');
            return res.redirect('/user/login?redirect='+req.originalUrl);
        }
        ucheck.AIManager(res,function (is) {
            if (!is) {
                req.flash('error', '对不起，您无权查看');
                return res.redirect('/');
            }
            next();
        });
    });
});

router.post('/*',function (req,res,next) {
    ucheck.hasLogin(res,function (has) {
        if (!has) {
            return res.json({
                message : '请先登录',
                code : -1,
                data : null
            });
        }
        ucheck.AIManager(res,function (is) {
            if (!is) {
                return res.json({
                    message : '您无权查看',
                    code : -1,
                    data : null
                });
            }
            next();
        });
    });
});

router.get('/', function(req, res, next) {
    var platform = req.query.platform;
    if (platform && platform.length > 0) {
        platform = platform.toLowerCase();
    } else  {
        platform = 'ios';
    }
    if (platform === 'android' && ucheck.canManagerAndroidSync(res)) {
        // 安卓
        req.session.addType = 2;
        Robots.getAll(function (err,robots) {
            GitUsers.getAll(function (e,g) {
                Repos.getAll(function (ee,r) {
                    res.render('component/list',{title:'Android模块管理',type:2,platform:'Android',robots:robots,gitusers:g,repos:r});
                });
            });
        });
    } else if (platform === 'ios' && ucheck.canManagerIOSSync(res)) {
        // ios
        req.session.addType = 1;
        Robots.getAll(function (err,robots) {
            GitUsers.getAll(function (e,g) {
                Repos.getAll(function (ee,r) {
                    res.render('component/list',{title:'iOS模块管理',type:1,platform:'iOS',robots:robots,gitusers:g,repos:r});
                });
            });
        });
    } else if (platform !== 'android' && platform !== 'ios') {
        // 非法
        req.flash('error', '平台信息有误，请核实');
        res.redirect('/');
    } else {
        req.flash('error', '对不起，您无权查看');
        res.redirect('/');
    }
});

router.post('/list',function (req,res,next) {
    Components.getListByType(req.session.addType,function (err,components) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : components
            });
        }
    });
});

router.post('/add',function (req,res,next) {
    var component = ({
        name : req.body['name'],
        url : req.body['url'],
        version : req.body['version'],
        gitUser : req.body['gitUser'] || null,
        repo : req.body['repo'],
        robots : JSON.parse(req.body['robots']),
        type : req.session.addType
    });
    Components.createUniqueName(component,function (err,com) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});

router.post('/edit',function (req,res,next) {
    var component = ({
        name : req.body['name'],
        url : req.body['url'],
        version : req.body['version'],
        gitUser : req.body['gitUser'] || null,
        repo : req.body['repo'],
        robots : JSON.parse(req.body['robots']),
        type : req.session.addType
    });
    var id = req.body['id'];
    Components.edit(id,component,function (err,com) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});

router.post('/get',function (req,res,next) {
     var id = req.body['id'];
     console.log('id ' + id);
     Components.getById(id, function (err,com) {
         if (err) {
             res.json({
                 message : err.message,
                 code : -1,
                 data : null
             });
         } else  {
             res.json({
                 message : '成功',
                 code : 0,
                 data : com
             });
         }
     })
});

router.post('/update', function(req, res, next) {
    var id = req.body['com_id'];
    var delId = req.body['del_id'];
    Components.getById(id, function (err,com) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {

            Delegater.getById(delId,function (err,delegater) {
                if (err) {
                    res.json({
                        message : err.message,
                        code : -1,
                        data : null
                    });
                } else {
                    res.json({
                        message : '成功',
                        code : 0,
                        data : com
                    });
                    // console.log(delegater);
                    // return;
                    var update = {
                        updating : true
                    };
                    Components.edit(com._id,update,function (err,data) {
                        if (err) {

                        } else  {

                        }
                    });

                    var startTime = new Date().getInterval();
                    var writeStream = new stream.writeStream(2,req.session.addType, com.name + '_' + com.version + '.log');
                    var version = com.version;

                    var gitUrl = com.url;
                    if (com.gitUser) {
                        var gituser = com.gitUser;
                        var urlComs = com.url.split('//');
                        var username = gituser.username;
                        username = username.replace(/@/g,'%40');
                        var passwd = gituser.passwd;
                        passwd = passwd.replace(/@/g,'%40');
                        gitUrl = urlComs[0] + '//' + username + ':' + passwd + '@' + urlComs[1];
                    }

                    var shell = "/Users/" + delegater.user + "/iPack/iOS/Scripts/update-component.sh " + com.name + ' ' + gitUrl + ' ' + com.version + ' ' + com.repo.name + ' ' + com.repo.url;

                    console.log('shell ' + shell);

                    scripter.execute(shell,function (data) {
                        // console.log(data);
                        writeStream.write(data);
                        if (data.indexOf('ipack-version|') >= 0) {
                            version = data.split('|')[1];
                            version = version.replace(/\r|\n/ig,"");
                        }
                        req.session.socketServer.sendMessage('update',com.name,{
                            message : data
                        });

                    },function (data) {
                        console.log(data);
                        writeStream.write(data);
                        req.session.socketServer.sendError('update',com.name,{
                            message : data
                        });
                    }, function (code) {
                        var endDate = new Date();
                        if (code === 0) {
                            writeStream.write('升级完成');
                            var endTime = endDate.getInterval();

                            var update = {
                                version : version,
                                updateSpend : parseInt(((com.updateCount * com.updateSpend) + (endTime - startTime)) / (com.updateCount + 1)),
                                updateCount : com.updateCount + 1,
                                lastUpdateSuccess : true,
                                lastUpdateTime : endDate,
                                lastUpdateUser : res.locals.user._id,
                                updating : false
                            };
                            Components.edit(com._id,update,function (err,data) {
                                if (err) {

                                } else  {
                                    if (com && com.robots) {
                                        com.robots.forEach(function (robot) {
                                            dingding.sendTextMessage(robot.token,com.name + '已经升级到' + version + '版本，请及时更新模块（更新人：' + res.locals.user.nickname + '）');
                                        })
                                    }
                                }
                            });
                            req.session.socketServer.sendMessage('update',com.name,{
                                message : 'ipack'
                            });
                        } else {
                            writeStream.write('升级失败');
                            var update = {
                                version : version,
                                lastUpdateSuccess : false,
                                lastUpdateTime : endDate,
                                lastUpdateUser : res.locals.user._id,
                                updating : false
                            };
                            Components.edit(com._id,update,function (err,data) {
                                if (err) {

                                } else  {

                                }
                            });
                            req.session.socketServer.sendError('update',com.name,{
                                message : 'ipack'
                            });
                        }

                    } ,delegater.user+'@'+delegater.ip);
                }
            });
        }
    });
});

router.get('/update/:id',function (req,res,next) {
    var id = req.params.id;
    Components.getById(id, function (err,com) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else {
            if (com) {
                if (com.updating) {
                    res.render('user/debug',{layout:'layout1.ejs',title:'正在升级'+com.name,action:'update',tag:com.name});
                } else {
                    res.json({
                        message : com.name + '并未在升级过程中',
                        code : -1,
                        data : null
                    });
                }
            } else {
                res.json({
                    message : '系统异常',
                    code : -1,
                    data : null
                });
            }

        }
    });
});

router.post('/delegater/list',function (req,res,next) {
    Delegater.getListByType(req.session.addType,function (err,delegaters) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : delegaters
            });
        }
    })
});

module.exports = router;
